package dmitrygusev.ratings.services.renders;

import java.util.List;

import dmitrygusev.io.StringUtils;
import dmitrygusev.nanoxml.XMLUtils;
import dmitrygusev.nanoxml.lite.XMLElement;
import dmitrygusev.ratings.model.Movie;
import dmitrygusev.ratings.model.MoviePack;
import dmitrygusev.ratings.model.Rating;
import dmitrygusev.ratings.services.MoviePacker;
import dmitrygusev.ratings.services.RatingQueryService.SearchMode;
import dmitrygusev.ratings.templates.TemplateLoader;

public class ResultsXhtmlRender {

	private int idCounter;
	
	public XMLElement render(List<Movie> movies, String query, SearchMode searchMode) {
		XMLElement responseXml = TemplateLoader.loadTemplate("xhtml-template.htm", "UTF-8");
		XMLElement queryFormXml = TemplateLoader.loadTemplate("query-form-template.htm", "UTF-8");
		
		fixCssLinks(responseXml);
		
		for (XMLElement img : responseXml.find("//[@src='../../../../war/images/comments.png']")) {
			img.setAttribute("src", "images/comments.png");
		}
		
		responseXml.find("//script[@src='../../../../war/js/script.js']").get(0).setAttribute("src", "js/script.js");
		
		responseXml.find("//title").get(0).setContent(query + " - Ratings Service");
		queryFormXml.findById("query").setAttribute("value", query);
		queryFormXml.findById("xml-format").removeAttribute("checked");
		queryFormXml.findById("xhtml-format").setAttribute("checked", "checked");
		
		if (searchMode == SearchMode.FULLTEXT) {
			queryFormXml.findById("search-mode").setAttribute("checked", "checked");
		}
		
		XMLElement queryDiv = responseXml.findById("query-form");
		queryDiv.setContent(null);
		queryDiv.addChild(queryFormXml);
		
		XMLElement resultsDiv = responseXml.findById("results");
		XMLElement movieDivTemplate = (XMLElement) resultsDiv.getChildren().get(0);
		resultsDiv.removeChild(movieDivTemplate);
		
		if (movies != null && ! movies.isEmpty()) {
			
			List<MoviePack> packs = new MoviePacker().packMovies(movies);
			
			resultsDiv.addChild(XMLUtils.createElement("p").setContent(String.format("Найдено %s фильмов.", packs.size())));
			
			for (MoviePack pack : packs) {
				XMLElement newMovieDiv = resultsDiv.addChild(movieDivTemplate.clone());
				
				newMovieDiv.findById("picture").updateId(idCounter++).setAttribute("src", StringUtils.isNullOrEmpty(pack.getCoverPicture()) ? "images/no-picture.png" : pack.getCoverPicture());
				
				newMovieDiv.findById("title1").updateId(idCounter++).setContent(pack.getTitle());
				newMovieDiv.findById("year").updateId(idCounter++).setContent(pack.getYear());
				
				XMLElement titleContainer = newMovieDiv.findById("title-container").updateId(idCounter++);
				XMLElement title2 = titleContainer.findById("title2").updateId(idCounter++);
				if (pack.isTitle2Available()) {
					title2.setContent(pack.getTitle2());
				} else {
					titleContainer.removeChild(title2);
				}
				
				XMLElement ratingsDiv = newMovieDiv.findById("ratings").updateId(idCounter++);
				
				XMLElement ratingDivTemplate = (XMLElement) ratingsDiv.getChildren().get(0);
				ratingsDiv.removeChildren();

				XMLElement commentsDiv = newMovieDiv.findById("comments").updateId(idCounter++);
				
				XMLElement commentsDivTemplate = (XMLElement) commentsDiv.getChildren().get(0);
				commentsDiv.removeChildren();

				for (Movie movie : pack.getMovies()) {
					for (Rating rating : movie.getRatings()) {
	
						XMLElement newRatingDiv = ratingsDiv.addChild(ratingDivTemplate.clone());
	
						newRatingDiv.findById("rating-source").updateId(idCounter++).
							setContent(
								movie.getSource()
										+ (rating.getType().equals("main") 
												? ""
												: "/" + rating.getType()));
						
						newRatingDiv.findById("rating-value").updateId(idCounter++).setContent(rating.getValue());
						newRatingDiv.findById("rating-votes").updateId(idCounter++).setContent(rating.getVotes());
					}
					
					XMLElement newCommentsDiv = commentsDiv.addChild(commentsDivTemplate.clone());
					
					newCommentsDiv.findById("comments-source").updateId(idCounter++).setContent(movie.getSource());
					newCommentsDiv.findById("comments-link").updateId(idCounter++).setAttribute("href", movie.getUrl());
					newCommentsDiv.findById("comments-count").updateId(idCounter++).setContent(movie.getCommentsCount());
				}
				
				if (ratingsDiv.getChildren().size() == 0) {
					ratingsDiv.addChild(XMLUtils.createElement("span").setContent("Нет рейтингов"));
				}
			}
		} else {
			resultsDiv.addChild(XMLUtils.createElement("p").setContent("Ничего не найдено."));
		}

		return responseXml;
	}

	public static void fixCssLinks(XMLElement xhtml) {
		//	Fix CSS/image paths: design-time -> run-time
		for (XMLElement link : xhtml.find("//[@rel='stylesheet']")) {
			String cssHref = link.getAttribute("href").toString();
			link.setAttribute("href", "css" + cssHref.substring(cssHref.lastIndexOf('/')));
		}
	}
	
}
